package com.swgk.core.base;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.appcompat.app.AppCompatActivity;

import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.barlibrary.ImmersionBar;
import com.swgk.core.BaseAppApplication;
import com.swgk.core.BaseAppHelper;
import com.swgk.core.R;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.base.net.NetBroadcastReceiver;
import com.swgk.core.helper.AppManagerHelper;
import com.swgk.core.util.LiuHaiPingUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SoftKeyBoardUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;

/**
 * Description:
 * Author zhengkewen
 * Time 2017/12/11
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "BaseActivity";
    private static final int MIN_CLICK_DELAY_TIME = 2000;
    private static long lastClickTime;
    public ImmersionBar immersionBar;
    private long lastBackpressTime;
    private NetBroadcastReceiver netBroadcastReceiver;

    protected abstract void initView();

    protected abstract void init();

    protected abstract void setupActivityComponent(AppComponent appComponent);

    protected  boolean statusBarDark() {
        return false;
    }

    protected abstract boolean exit();

    protected abstract boolean registerNet();

    protected abstract void connectNetWork();

    protected abstract void disconnectNetWork();

    public abstract void onMultiClick(View v);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActivityComponent(BaseAppHelper.get().getAppComponent());
        immersionBar = ImmersionBar.with(this)
                .statusBarDarkFont(statusBarDark())
                .fitsSystemWindows(false)
                .keyboardEnable(false)
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        immersionBar.init();
        //注入ARouter
        ARouter.getInstance().inject(this);
        initView();
        View liuHaiView = findViewById(R.id.liuhai_status_view);
        if (liuHaiView != null) {
            liuHaiView.getLayoutParams().height = LiuHaiPingUtils.getStatusBarHeight(this);
        }
        init();

        if (registerNet()) {
            registerNetBroadcast();
        }
    }

    private void registerNetBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        netBroadcastReceiver = new NetBroadcastReceiver(status -> {
            if (status) {
                connectNetWork();
            } else {
                disconnectNetWork();
            }
        });
        //注册广播接收
        registerReceiver(netBroadcastReceiver, filter);
    }

    protected void closeKeybord() {
        if (getCurrentFocus() != null) {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected void closeKeybord(View view) {
        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(view
                                .getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    public void onClick(View v) {
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            lastClickTime = curClickTime;
            onMultiClick(v);
        }
    }

    protected void jumpActivity(FragmentActivity activity, Class<? extends Activity> cls) {
        Intent intent = new Intent(activity, cls);
        activity.startActivity(intent);
    }

    protected void jumpActivityFinish(FragmentActivity activity, Class<? extends Activity> cls) {
        Intent intent = new Intent(activity, cls);
        activity.startActivity(intent);
        activity.finish();
    }

    protected void dial(String number) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + number + "\""));
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        if (exit()) {
            long pressTime = new Date().getTime();
            if (lastBackpressTime > 0 && (pressTime - lastBackpressTime < 2000)) {
                super.onBackPressed();
                this.finish();
            } else {
                lastBackpressTime = pressTime;
                MToast.showToast(this, "再点一次退出应用");
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (registerNet()) {
            unregisterReceiver(netBroadcastReceiver);
        }
        if (immersionBar != null){
            //调用该方法，防止内存泄漏
            immersionBar.destroy();
        }
    }

    /**
     * 重写getResources()方法，让APP的字体不受系统设置字体大小影响
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            //调用方法判断是否需要隐藏键盘
            SoftKeyBoardUtil.hideKeyboard(ev, view, BaseActivity.this);
        }
        return super.dispatchTouchEvent(ev);
    }

    public abstract void loading();

    public abstract void error();

    public abstract void success();
}
